package books4all

import org.springframework.dao.DataIntegrityViolationException
import grails.plugins.springsecurity.Secured

class ImageController {
	
	def springSecurityService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

	@Secured(['ROLE_ADMIN'])
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [imageInstanceList: Image.list(params), imageInstanceTotal: Image.count()]
    }
	
	def listPerso() {
		def courant = springSecurityService.currentUser
		String username = courant.username
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[imageInstanceList: User.findByUsername(username).images, imageInstanceTotal: User.findByUsername(username).images.size()]
	}

    def create() {
        [imageInstance: new Image(params)]
    }

    def save() {
        def imageInstance = new Image(params)
		def courant = springSecurityService.currentUser
		String username = courant.username
		User.findByUsername(username).addToImages(imageInstance)
        if (!imageInstance.save(flush: true)) {
            render(view: "create", model: [imageInstance: imageInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'image.label', default: 'Image'), imageInstance.id])
        redirect(action: "showPerso", id: imageInstance.id)
    }

	@Secured(['ROLE_ADMIN'])
    def show() {
        def imageInstance = Image.get(params.id)
        if (!imageInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'image.label', default: 'Image'), params.id])
            redirect(action: "list")
            return
        }

        [imageInstance: imageInstance]
    }
	
	def enleverList() {
		def courant = springSecurityService.currentUser
		def imageI = Image.get(params.id)
		String username = courant.username
		if(User.findByUsername(username).avatar.equals(imageI))
			User.findByUsername(username).avatar = null
		else {
			User.findByUsername(username).removeFromImages(Image.findById(imageI.id))
			Image.findById(imageI.id).delete(flush: true)
		}
		redirect(action: "listPerso")
	}
	
	def showPerso() {
		def imageInstance = Image.get(params.id)
		if (!imageInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'image.label', default: 'Image'), params.id])
			//redirect(action: "delete")
			redirect(action: "listPerso")
			return
		}

		[imageInstance: imageInstance]
	}
	
	def showImgAmi() {
		def imageInstance = Image.get(params.id)
		if (!imageInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'image.label', default: 'Image'), params.id])
			//redirect(action: "delete")
			redirect(action: "listPerso")
			return
		}

		[imageInstance: imageInstance]
	}

    def edit() {
        def imageInstance = Image.get(params.id)
        if (!imageInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'image.label', default: 'Image'), params.id])
            redirect(action: "list")
            return
        }

        [imageInstance: imageInstance]
    }

    def update() {
        def imageInstance = Image.get(params.id)
        if (!imageInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'image.label', default: 'Image'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (imageInstance.version > version) {
                imageInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'image.label', default: 'Image')] as Object[],
                          "Another user has updated this Image while you were editing")
                render(view: "edit", model: [imageInstance: imageInstance])
                return
            }
        }

        imageInstance.properties = params

        if (!imageInstance.save(flush: true)) {
            render(view: "edit", model: [imageInstance: imageInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'image.label', default: 'Image'), imageInstance.id])
        redirect(action: "show", id: imageInstance.id)
    }

    def delete() {
        def imageInstance = Image.get(params.id)
        if (!imageInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'image.label', default: 'Image'), params.id])
            redirect(action: "list")
            return
        }

        try {
            imageInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'image.label', default: 'Image'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'image.label', default: 'Image'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
	
	def viewImageId = {
		def image = User.get(params.id).avatar
		byte[] img = image.data
		response.contentType = "image/jpeg"
		response.outputStream << img
	}
	
	def viewImage = {
		def image = Image.get(params.id)
		byte[] img = image.data
		response.contentType = "image/jpeg"
		response.outputStream << img
	}
}
